﻿using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Permission;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.ListBillPlugin.GFT
{
    [Description("GFT:生产计划单跳层程序"), HotUpdate]
    public class ListPlan : AbstractListPlugIn
    {
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            switch (e.BarItemKey)
            {
                case "tbsjump":
                case "tbjump":
                    {
                        PermissionAuthResult iResult = PermissionServiceHelper.FuncPermissionAuth(this.Context, new BusinessObject() { Id = "PLN_PLANORDER" }, PermissionConst.New);
                        if (!iResult.Passed)
                        {
                            this.View.ShowMessage("你没有修改计划订单的权限)！");
                            return;
                        }
                        ListSelectedRowCollection selectRows = this.ListView.SelectedRowsInfo;
                        StringBuilder errorsb = new StringBuilder();
                        StringBuilder sb = new StringBuilder();
                        StringBuilder billnolist = new StringBuilder();
                        int changedts = 0;
                        for (int i = 0; i < selectRows.Count; i++)
                        {
                            //计划单号
                            string number = selectRows[i].BillNo.ToString();
                            //计划单业务状态
                            string ywstatus = "";//selectRows[i].DataRow["FRELEASESTATUS"].ToString();
                            try { ywstatus = selectRows[i].DataRow["FRELEASESTATUS"].ToString(); }
                            catch { ywstatus = DBServiceHelper.ExecuteScalar<string>(this.Context, string.Format("select  FRELEASESTATUS from T_PLN_PLANORDER  where FBILLNO='{0}' ", number), ""); }
                            if (!number.IsEmpty() && ywstatus == "0")
                            {
                                string result = DBServiceHelper.ExecuteScalar<string>(this.Context, string.Format("exec yls_plnjump '{0}','jump'", number), "1");
                                switch (result)
                                {
                                    case "1":

                                        //取BOM最大序号
                                        int fseq = DBServiceHelper.ExecuteScalar<int>(this.Context, string.Format("select max(a.fseq) from T_PLN_PLBOMENTRY a inner join T_PLN_PLANORDER b on a.fid=b.fid where b.FBILLNO='{0}'", number), 0);
                                        IDBService service = Kingdee.BOS.Contracts.ServiceFactory.GetService<IDBService>(this.Context);
                                        StringBuilder sql = new StringBuilder();
                                        sql.AppendLine("/*dialect*/ ");
                                        //增加跳层引起的向上转移的物料
                                        //将下层物料向上转移到要层的BOM中
                                        using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, string.Format(" exec yls_jumpmaterialts '{0}'", number)))
                                        {
                                            int k = 0;
                                            while (rd.Read())
                                            {
                                                Int32[] maxFID = service.GetSequenceInt32(this.Context, "T_PLN_PLBOMENTRY", 1);
                                                sql.AppendLine("insert into T_PLN_PLBOMENTRY(fid,FENTRYID,FMATERIALID,FMATERIALTYPE,FDOSAGETYPE,FAUXPROPID,FUSERATE,FNUMERATOR,FDENOMINATOR,FDEMANDDATE,FUNITID,FSTDQTY,FNEEDQTY,FMUSTQTY,FFIXSCRAP,");
                                                sql.AppendLine("FSCRAPRATE,FBOMID,FSTOCKID,FSTOCKLOCID,FWORKCALID,FBOMENTRYID,FBASEUNITID,FBASESTDQTY,FBASENEEDQTY,FBASEFIXSCRAPQTY,FBASENUMERATOR,FBASEDENOMINATOR,FISSUBSITEM,FPATHENTRYID,FOldEtnryId,FISJUMPADD,fseq)");
                                                sql.AppendLine(string.Format("select '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',", rd[0], maxFID[0], rd[2], rd[3], rd[4], rd[5], rd[6], rd[7], rd[8], rd[9], rd[10], rd[11], rd[12], rd[13], rd[14]));
                                                sql.AppendLine(string.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',{15},{16}", rd[15], rd[16], rd[17], rd[18], rd[19], rd[20], rd[21], rd[22], rd[23], rd[24], rd[25], rd[26], rd[27], rd[28], rd[1], 1, fseq + k + 1));
                                                k += 1;
                                            }
                                        }
                                        //写入BOM扩展表
                                        sql.AppendLine(string.Format(" exec yls_jumpmaterialts_c '{0}'", number));
                                        if (sql.ToString().Length > 30)
                                        {
                                            DBServiceHelper.ExecuteReader(this.Context, sql.ToString());
                                        }
                                        sb.AppendLine(string.Format("计划单号【{0}】执行跳层操作成功！", number));
                                        changedts += 1;
                                        break;
                                    case "0":
                                        errorsb.AppendLine(string.Format("计划单号【{0}】执行跳层操作失败！", number));
                                        break;
                                    case "2":
                                        errorsb.AppendLine(string.Format("计划单号【{0}】没有下层计划单，无需跳层！", number));
                                        break;
                                    case "3":
                                        errorsb.AppendLine(string.Format("计划单号【{0}】有下层计划单不在计划状态，不能执行跳层操作！", number));
                                        break;
                                }
                            }
                            else
                            { errorsb.AppendLine(string.Format("计划单号【{0}】的业务状态不是‘计划’状态，不可以执行跳层操作！", number)); }
                        }
                        if (changedts > 0)
                        { this.ListView.Refresh(); }
                        if (sb.ToString() != "")
                        { this.View.ShowMessage(sb.ToString()); }
                        if (errorsb.ToString() != "")
                        { this.View.ShowErrMessage(errorsb.ToString()); }
                        break;
                    }

                case "tbunjump":
                    {

                        ListSelectedRowCollection selectRows = this.ListView.SelectedRowsInfo;
                        StringBuilder errorsb = new StringBuilder();
                        StringBuilder sb = new StringBuilder();
                        StringBuilder billnolist = new StringBuilder();
                        int changedts = 0;
                        for (int i = 0; i < selectRows.Count; i++)
                        {
                            //计划单号
                            string number = selectRows[i].BillNo.ToString();
                            //计划单业务状态
                            string tc = "", ywstatus = "";//selectRows[i].DataRow["FRELEASESTATUS"].ToString();
                            try { tc = selectRows[i].DataRow["F_TC"].ToString(); }
                            catch { tc = DBServiceHelper.ExecuteScalar<string>(this.Context, string.Format("select  F_tc from T_PLN_PLANORDER  where FBILLNO='{0}' ", number), ""); }
                            try { ywstatus = selectRows[i].DataRow["FRELEASESTATUS"].ToString(); }
                            catch { ywstatus = DBServiceHelper.ExecuteScalar<string>(this.Context, string.Format("select  FRELEASESTATUS from T_PLN_PLANORDER  where FBILLNO='{0}' ", number), ""); }
                            if (!number.IsEmpty() && tc != "True")
                            { errorsb.AppendLine(string.Format("计划单号【{0}】不在‘已跳层’状态，不可以执行反跳层操作！", number)); }
                            if (!number.IsEmpty() && tc == "True")
                            {
                                if (ywstatus == "0")
                                {
                                    string result = DBServiceHelper.ExecuteScalar<string>(this.Context, string.Format("exec yls_plnjump '{0}','unjump'", number), "1");
                                    switch (result)
                                    {
                                        case "1":
                                            sb.AppendLine(string.Format("计划单号【{0}】执行反跳层操作成功！", number));
                                            changedts += 1;
                                            break;
                                        case "0":
                                            errorsb.AppendLine(string.Format("计划单号【{0}】执行反跳层操作失败！", number));
                                            break;
                                        case "4"://
                                            errorsb.AppendLine(string.Format("计划单号【{0}】下层计划单已进行其它操作,不能执行反跳层操作！", number));
                                            break;
                                    }
                                }
                                else
                                { errorsb.AppendLine(string.Format("计划单号【{0}】不在计划状态，不能执行反跳层操作！", number)); }
                            }
                        }
                        if (changedts > 0)
                        { this.ListView.Refresh(); }
                        if (sb.ToString() != "")
                        { this.View.ShowMessage(sb.ToString()); }
                        if (errorsb.ToString() != "")
                        { this.View.ShowErrMessage(errorsb.ToString()); }
                        break;
                    }

            }
        }
        public override void OnFormatRowConditions(ListFormatConditionArgs args)
        {
            base.OnFormatRowConditions(args);
            FormatCondition fc = new FormatCondition();
            fc.ApplayRow = true;
            if (args.DataRow.ColumnContains("F_tc"))
            {
                if (args.DataRow["F_tc"].ToString() == "True")
                { fc.BackColor = ColorTranslator.ToHtml(System.Drawing.Color.Yellow); }
                string ywstatus = "";
                try { ywstatus = args.DataRow["FRELEASESTATUS"].ToString(); }
                catch
                {
                    string number = args.DataRow["BillNo"].ToString();
                    ywstatus = DBServiceHelper.ExecuteScalar<string>(this.Context, string.Format("select  FRELEASESTATUS from T_PLN_PLANORDER  where FBILLNO='{0}' ", number), "");
                }

                if (ywstatus == "8")
                {
                    fc.BackColor = ColorTranslator.ToHtml(System.Drawing.Color.LightYellow);
                }
                args.FormatConditions.Add(fc);
            }
        }
    }
}
